package com.mldong.flow.engine.handlers.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.mldong.flow.engine.core.Execution;
import com.mldong.flow.engine.entity.ProcessTask;
import com.mldong.flow.engine.enums.TaskStateEnum;
import com.mldong.flow.engine.handlers.IHandler;
import com.mldong.flow.engine.model.TaskModel;

import java.util.Date;

/**
 * 创建任务处理器
 * @author mldong
 * @date 2023/5/16
 */
public class CreateTaskHandler implements IHandler {
    private TaskModel taskModel;
    public CreateTaskHandler(TaskModel taskModel) {
        this.taskModel = taskModel;
    }
    @Override
    public void handle(Execution execution) {
        Date now = new Date();
        ProcessTask processTask = new ProcessTask();
        processTask.setTaskName(this.taskModel.getName());
        processTask.setDisplayName(this.taskModel.getDisplayName());
        processTask.setTaskState(TaskStateEnum.DOING.getCode());
        processTask.setProcessInstanceId(execution.getProcessInstanceId());
        processTask.setVariable(JSONUtil.toJsonStr(execution.getArgs()));
        processTask.setCreateTime(now);
        processTask.setUpdateTime(now);
        execution.setProcessTask(processTask);
        System.out.println("创建任务："+processTask.getTaskName()+","+processTask.getDisplayName());
        execution.addTask(processTask);
        // 调用流程引擎方法保存流程任务入库
        execution.getEngine().processTaskService().saveProcessTask(processTask);
    }
}
